package cn.chenfei.jfx.common;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author ChenFei
 * @date 2022/4/9
 */
public class QrUtil {

    static final String FORMAT = "png";

    public static void writeToStream(String filePath, int width, int height, String text) {
         /*
           定义二维码的参数
        */
        HashMap hashMap = new HashMap();
        // 设置二维码字符编码
        hashMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 设置二维码纠错等级
        hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 设置二维码边距
        hashMap.put(EncodeHintType.MARGIN, 1);

        try {
            // 开始生成二维码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hashMap);
            // 导出到指定目录
            MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, new FileOutputStream(filePath));
            //MatrixToImageWriter.toBufferedImage(bitMatrix);
        } catch (WriterException | IOException e) {
            e.printStackTrace();
        }
    }
}
